import { Ref, useImperativeHandle, forwardRef, useCallback } from 'react';
import { Button, Space } from 'antd-mobile';
import { connect, mapProps } from '@formily/react';
import { InbizIcon, useEvents } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import { defaultProps } from '../../designer/schema';
import api from '../web/api';
import styles from './index.less';



type Iprops = {
  lang: string;
  isTpl: boolean;
  prefixCls?: string;
  disabled?: boolean;
  readOnly?: boolean;
  buttontype?: any;
  buttoncolor?: string; // 非驼峰写法老数据，驼峰写法新数据（兼容适配用，写法不对，请勿模仿）
  buttonColor?: string;
  textcolor?: string;
  title?: any;
  icon?: any;
  style?: object;
  inbiz?: any;
  wapButtonShowTyps?: 'solid' | 'outline' | 'none';
  emit?: {
    /** 按钮组件点击时触发 */
    (type: 'onClick', action: 'submit' | 'rest' | 'custom'): void;
  };
} & {
  callBackEvents: {
    /** 按钮组件点击前触发 return false | true
     * return false时拦截按钮操作 */
    onBeforeOperationAsync: (action: string) => boolean;
  };
} & typeof defaultProps;
type ref = Ref<ReturnType<typeof api>>;

const EformButton = forwardRef((props: Iprops, ref: ref) => {
  const {
    buttontype,
    buttoncolor,
    textcolor,
    title,
    icon,
    inbiz,
    readOnly,
    disabled,
    buttonColorType,
    buttonColor,
    wapButtonShowTyps = 'solid',
    // buttonBorder = 2, // 解决老版本显示的圆角的问题？
    style,
  } = props;

  const [configEvents] = useEvents(props.callBackEvents, props.emit);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents),
    }),
    [],
  );

  // 按钮点击
  const handleClick = async () => {
    props.emit?.('onClick', buttontype);
    switch (buttontype) {
      case 'submit':
        inbiz?.submit?.();
        break;
      case 'reset':
        inbiz?.reset?.();
        break;
      default:
        break;
    }
  };

  const getButtonColorFunction = useCallback(() => {
    let resultStyle = {};
    switch (wapButtonShowTyps) {
      case 'solid':
        resultStyle = {
          // borderRadius: buttonBorder,
          ...style,
          background:
            buttonColorType === 'system' || !buttonColorType
              ? 'var(--inbiz-color-primary)'
              : buttonColor,
          borderColor:
            buttonColorType === 'system' || !buttonColorType
              ? 'var(--inbiz-color-primary)'
              : buttonColor,
        };
        break;
      case 'none':
        resultStyle = {
          // borderRadius: buttonBorder,
          style,
          color: buttonColorType === 'system' || !buttonColorType ? '' : buttonColor,
        };
        break;
      default:
        resultStyle = {
          // borderRadius: buttonBorder,
          ...style,
          borderColor: buttonColorType === 'system' || !buttonColorType ? '' : buttonColor,
          color: buttonColorType === 'system' || !buttonColorType ? '' : buttonColor,
        };
        break;
    }
    return resultStyle;
  }, [buttonColorType, wapButtonShowTyps, buttonColor, style]);

  return (
    <div
      // style={{ display: 'flex', justifyContent: 'center', marginBottom: '22px' }}
      className={`${styles.buttonBox}`}
    >
      <Button
        block
        fill={wapButtonShowTyps}
        color={'primary'}
        disabled={readOnly || disabled}
        style={
          readOnly || disabled
            ? undefined
            : buttoncolor && !props.wapButtonShowTyps // 兼容老版本（以前拖拽的按钮）
            ? { background: buttoncolor, borderColor: buttoncolor, ...style }
            : getButtonColorFunction()
        }
        onClick={handleClick}
        // icon={icon.type && <InbizIcon type={icon?.type} />}
      >
        {icon.type ? (
          <Space style={{ display: 'flex', justifyContent: 'center' }}>
            <InbizIcon
              type={icon?.type}
              style={
                icon?.color && !props.wapButtonShowTyps // 兼容老版本（以前拖拽的按钮）
                  ? { color: icon?.color ? icon?.color : '#000', fontSize: icon?.size }
                  : { fontSize: icon?.size }
              }
            />
            <div style={textcolor && !props.wapButtonShowTyps ? { color: textcolor } : {}}>
              {title.status == true && getMessage(title.value)}
            </div>
          </Space>
        ) : (
          <div className="defaultText" style={textcolor && !props.wapButtonShowTyps ? { color: textcolor} : {}}>
            {title.status == true && getMessage(title.value)}
          </div>
        )}
      </Button>
    </div>
  );
});

export default connect(
  EformButton,
  mapProps({}, (props, field) => {
    // field.decoratorProps.addonAfter = props.addonAfter;
    return { ...props };
  }),
);
